package cn.com.klun.tjy.task;

import cn.com.klun.tjy.common.factory.SpringBeanFactory;
import cn.com.klun.tjy.dao.entity.TblAllStockInfo;
import cn.com.klun.tjy.dao.mapper.ser.TblAllStockInfoSerMapper;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SpiderJob implements Job {

    private Logger logger = LoggerFactory.getLogger(SpiderJob.class);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        TblAllStockInfoSerMapper tblAllStockInfoSerMapper = SpringBeanFactory.getBean(TblAllStockInfoSerMapper.class);

        // 这是要执行的任务
        logger.info("定时执行任务，开始时间"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(new Date()));
        TblAllStockInfo tblAllStockInfo = new TblAllStockInfo();
        List<TblAllStockInfo> tblAllStockInfos = new ArrayList<>();
        try {
            tblAllStockInfos = tblAllStockInfoSerMapper.queryList(tblAllStockInfo);
        }catch (Exception e){
            logger.error("查询数据库异常,异常信息[{}]",e);
        }
        int listSize = tblAllStockInfos.size();
        // 获取当前时间
        String sysDate = new SimpleDateFormat("yyyy年MM月dd日").format(new Date());
        File dest = new File("D:/data/"+sysDate);
        if(!dest.exists()  && !dest .isDirectory()){
            dest.mkdirs();// 如果不存在则创建
        }
        int i = 1;
        for (TblAllStockInfo stockInfo: tblAllStockInfos) {
            String stockCode = stockInfo.getEx()+stockInfo.getStockCode();
            String alterUrl = "http://quote.eastmoney.com/"+stockCode+".html";
            String baseName = stockInfo.getName();
            if("*".equals(baseName.substring(0,1))){
                baseName = baseName.substring(1);
            }
            // get project path
            // String relativelyPath=System.getProperty("user.dir");
            String path = "D:/data/"+sysDate+"/"+stockCode+"_"+baseName+"_"+stockInfo.getIndustry()+".html";
            try{
                //保存到本地的网页地址
                int result = JavaSpider.Save_Html(alterUrl, path);
                if(1 == result){
                    //解析本地的网页地址
                    if(1 == i){
                        // 在解析网页 第一次 时候 放入 大盘数据
                    }
                    JavaSpider.Get_Localhtml(path);
                    logger.info("保存{}页面成功,count[{}]",stockCode+baseName,i++);
                    continue;
                }
                if(-1 == result){
                    // set stock exception infomation to the table exception
                }
            }catch (Exception e){
                logger.info("保存页面失败,异常信息{}",e.getMessage());
            }
        }
    }
}
